package com.tianqu.tms.www.transfer.controller;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.util.car.CarInformationApi;
import com.tianqu.tms.core.util.car.IdentifyModelByVinBean;
import com.tianqu.tms.dto.TmsCarmodelVinDto;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.CarModelInfo;
import com.tianqu.tms.entity.CarStyle;
import com.tianqu.tms.entity.TransferAcceptedInfo;
import com.tianqu.tms.entity.TransferPersonalCarInfo;
import com.tianqu.tms.entity.TransferProcessHistory;
import com.tianqu.tms.www.transfer.viewhelper.TransferRgInputViewHelper;

/**
 * 
 * 进入过户登记录入结果页面Controller
 * 
 * @author Administrator
 * 
 */

public class TransferRgInputResultController extends TmsController {
	private Logger logger = Logger.getLogger(TransferRgInputResultController.class);

	private static final String SYSPATH = "sysPath";//

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = getTxController();
		try {
			controller.begin();
			TransferRgInputViewHelper view = (TransferRgInputViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
			TmsUserProfile profile = uc.getUserProfile();
			uc.setAttribute("updateButtonBsFlag", view.getUpdateButtonBsFlag());
			String reFlag = "";
			reFlag = (String)uc.getAttribute("reFlag");
 
			if(view.getMarketType() == 1)
			{
				Car car = new Car();
				car = car.findCarBySerial(view.getBasicCarId());
				car = setEntityFromViewhelper(car, view);
				car.setUpdateUserId(profile.getUniqueId());
				if(!"2".equals(view.getUpdateButtonBsFlag())){
					car.setStatus(3);
				}
				car.updateMarketInfoByLicensePlate(car);				
			}
			if(view.getMarketType() == 2)
			{
				TransferPersonalCarInfo person = new TransferPersonalCarInfo();
				person = person.getPersonalCarInfoBySerial(view.getBasicCarId());
				person = setEntityFromViewhelper1(person, view);
				person.setUpdateUserId(profile.getUniqueId());
				if(!"2".equals(view.getUpdateButtonBsFlag())){
					person.setStatus(3);
				}
				person.updateCarBaseInfo(person);			
			}
			TransferAcceptedInfo accept = new TransferAcceptedInfo();
			accept = accept.getAcceptInfoBySerial(view.getSerial(),"");
			accept.setSerial(view.getSerial());
			accept.setVin(view.getVin());
			accept.setAgentName(view.getAgentName());
			accept.setAgentPhone(view.getAgentPhone());
			accept.setAgentOwnerIdCardNo(view.getAgentOwnerIdCardNo());
			accept.setAgentAddress(view.getAgentAddress());
			accept.setMaterialImages1(view.getMaterialImages1());
			accept.setMaterialImages2(view.getMaterialImages2());
			accept.setMaterialImages3(view.getMaterialImages3());
			accept.setMaterialImages4(view.getMaterialImages4());
			accept.setMaterialImages5(view.getMaterialImages5());
			accept.setOwnersGroupPhoto(view.getOwnersGroupPhoto());
			accept.setUpdateUserId(profile.getUniqueId());
			accept.setDb_printUserId(profile.getUniqueId());
			accept.setWaitForStatus(accept.getWaitForStatus());
			// add by huangheli at 20150921 start
			accept.setMemberId(view.getMemberId());
			//  add by huangheli at 20150921 start
			String sysPath = (String) uc.getAttribute(SYSPATH);
			
			//20160409
			if(!StringUtil.isNullOrBlank(view.getNewCarOwner()) && view.getNewCarOwner().length()>=5){
				accept.setNewOwnerType(2);//企业
				accept.setNewOwnerOrgNo(view.getNewIdentification());
		    } else if(!StringUtil.isNullOrBlank(view.getNewCarOwner()) && view.getNewCarOwner().length() < 5){
		    	accept.setNewOwnerType(1);//个人
		    	accept.setNewcarOwnerIdCardNo(view.getNewIdentification());
		    } 
			 
			accept.setNewcarOwner(view.getNewCarOwner());
			accept.setNewOwnerAddress(view.getNewOwnerAddress());
			accept.setNewOwnerPhone(view.getNewOwnerPhone());
			accept.setZipCode(view.getZipCode());
			accept.setMailAddress(view.getMailAddress());
			accept.setNewAgentPhone(view.getNewAgentPhone());
			accept.setNewAgentName(view.getNewAgentName());
			accept.setNewAgentOwnerIdCardNo(view.getNewAgentOwnerIdCardNo());
			accept.setNewAgentAddress(view.getNewAgentAddress());
			
			//20160409
			if(!StringUtil.isNullOrBlank(view.getCarOwner()) && view.getCarOwner().length()>=5){
				accept.setOwnerType(2);//企业
				accept.setOwnerOrgNo(view.getIdentification());
		    } else if(!StringUtil.isNullOrBlank(view.getCarOwner()) && view.getCarOwner().length() < 5){
		    	accept.setOwnerType(1);//个人
		    	accept.setCarOwnerIdCardNo(view.getIdentification());
		    } 
			
			accept.setOwnerPhone(view.getOwnerPhone());
			accept.setOwnerAddress(view.getOwnerAddress());
			accept.setCarOwner(view.getCarOwner());
			
			if(view.getGainType()!=null && !"".equals(view.getGainType()))
			{
				accept.setGainType(Integer.parseInt(view.getGainType()));
			}
			accept.setCarMarketIn(view.getCarMarketIn());
			if(!"省".equals(view.getMoveOutProvince()))
			{
				accept.setMoveOutProvince(view.getMoveOutProvince());
			}else{
				accept.setMoveOutProvince("");
			}
			if(!"市".equals(view.getMoveOutCity()))
			{
				accept.setMoveOutCity(view.getMoveOutCity());
			}else{
				accept.setMoveOutCity("");
			}
			
			if(view.getTransferType()!=null && !"".equals(view.getTransferType()))
			{
				accept.setTransferType(Integer.parseInt(view.getTransferType()));
			}
			accept.setNewOwnerTelPhone(view.getNewOwnerTelPhone());
			if(view.getTransferPrice()!=null && !"".equals(view.getTransferPrice()))
			{
				accept.setTransferPrice(Integer.parseInt(StringUtil.removeDH(view.getTransferPrice())));
			}else{
				accept.setTransferPrice(0);
			}
			if(view.getPrice()!=null && !"".equals(view.getPrice()))
			{
				accept.setPrice(Integer.parseInt(StringUtil.removeDH(view.getPrice())));
			}
			accept.setTaxNo(view.getTaxNo());
			accept.setAttnId(view.getAttnId());
			accept.setRemark(view.getRemark());
			
			String saveBsFlag = (String)uc.getAttribute("saveBsFlag");
			TransferAcceptedInfo accept1 = accept.findPirntNumBySerial(view.getSerial());

            // #104 start
            boolean updateMatch = updateMatch(accept,view);
            // #104 e n d
			TransferProcessHistory history = new TransferProcessHistory();
			if("1".equals(saveBsFlag)||"3".equals(saveBsFlag))
			{
				//print
				accept.setZy_printnum(accept1.getZy_printnum());
				accept.setZy_printTime(accept1.getZy_printTime());
				accept.setZy_printUserId(accept1.getZy_printUserId());
				if(!"2".equals(view.getUpdateButtonBsFlag()))
				{
					accept.setZy_printnum(accept1.getZy_printnum()+1);
					accept.setZy_printUserId(profile.getUniqueId());
					accept.setZy_printTime(DateUtil.getCurrentTime1());
					
					//workload:3.1.2
					if("3".equals(view.getSourceType()))
					{
						accept.setStatus(10);
						accept.setCheckFileStatus(102);
					}else{
						accept.setStatus(6);
					}				
				}
				if(view.getSourceType()!=null && !"".equals(view.getSourceType()))
				{
					accept.setSourceType(Integer.parseInt(view.getSourceType()));
				}
				accept.setPreTransfer(2);
				accept.updateAcceptInfoAtGh(accept, sysPath, updateMatch);
				// #104 start
				TmsCarmodelVinDto tcmd = new TmsCarmodelVinDto();
				tcmd.setModelId(accept.getCarStyleId());
				tcmd.setVin(accept.getVin());
				CarModelInfo.getInstance().carmodelVinInsert(tcmd);
				// #104 e n d
				history.setSerial(view.getSerial());
				if("3".equals(view.getSourceType()))
				{
					history.setBusinessType(10);
				}else{
					history.setBusinessType(6);
				}
				if("2".equals(view.getUpdateButtonBsFlag()))
				{
					history.setBusinessType(41);
				}
				history.setInsertUserId(profile.getUniqueId());
				history.setReason("");
				history.insertHisInfoAtAssess(history);
			}
			if("2".equals(saveBsFlag))
			{
				
				if(reFlag != null && reFlag != ""){
					history.setSerial(view.getSerial());
					history.setBusinessType(45);
					history.setInsertUserId(profile.getUniqueId());
					history.setReason("");
					history.insertHisInfoAtAssess(history);
				}else{
					history.setSerial(view.getSerial());
					history.setBusinessType(5);
					history.setInsertUserId(profile.getUniqueId());
					history.setReason("");
					history.insertHisInfoAtAssess(history);
				}
				accept.setStatus(accept.getStatus());
				//save
				accept.setZy_printnum(accept1.getZy_printnum());
				accept.setZy_printTime(accept1.getZy_printTime());
				accept.setZy_printUserId(accept1.getZy_printUserId());
				accept.setPreTransfer(accept.getPreTransfer());
				if(view.getSourceType()!=null && !"".equals(view.getSourceType()))
				{
					accept.setSourceType(Integer.parseInt(view.getSourceType()));
				}
				accept.updateAcceptInfoAtGh(accept, sysPath,updateMatch);
			}
			 
			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}
		logger.debug(this.getClass().getName() + "#execute was completed.");
	}
	
	/**
	 * # 如果对应的车款是否配对（isMatch）为“1：未匹对”，那么利用页面输入的车架号调用车型信息更新接口（具体参照车型信息更新接口sheet），
	 * 如果获得对应车辆型号id值，
	 * 那么对应更新车辆品牌Id（vendorId）、
	 * 车系Id（brandId）、
	 * 车辆款式Id（carStyleId），
	 * 车辆名称（carName）为通过车辆款式Id从车辆款式表（tms_car_style）取出的款式名称（styleName），
	 * 同时更新车款是否配对（isMatch）为“2：匹对”
	 * 
	 * @param accept
	 * @param view
	 * @throws TmsDaoException 
	 */
	private boolean updateMatch(TransferAcceptedInfo accept,TransferRgInputViewHelper view) throws TmsDaoException {
	    boolean rtn = false;
	    CarStyle car = null;
	    if (accept.getIsMatch() == 1) {
	        // 通过vin从tms_carModel_Vin找modelid 这个找到就是carstyleid
	        TmsCarmodelVinDto carmodelVin = CarModelInfo.getInstance().carmodelVinGet(null,view.getVin());
            if(carmodelVin != null && !StringUtil.isNullOrBlank(carmodelVin.getModelId())){
                car = CarStyle.getInstance().findCarStyleInfoByModelId(carmodelVin.getModelId());
                if(car != null && !StringUtil.isNullOrBlank(car.getCarStyleId())){
                    accept.setIsMatch(2);
                    accept.setCarName(car.getCarStyleName());
                    accept.setCarStyleId(car.getCarStyleId());
                    accept.setBrandId(car.getBrandId());
                    accept.setVendorId(car.getVendorId());
                    rtn = true;
                }
            }
            if (car == null) {
                // 用che300获取的modelI去搜tms_car_style.modelIdOthe，有就可以关联，没有就空着就行
                IdentifyModelByVinBean info = CarInformationApi.getIdentifyModelByVin(view.getVin());
                // 而che300获取的是che300的id，还需要转换下，用车300的id去tms_car_style表搜modelIdOther，然后获取到id，也是carstyleid
                if(!StringUtil.isNullOrBlank(info.getModelId())){
                    car = CarStyle.getInstance().findCarStyleInfo(info.getModelId());
                    if (car != null && !StringUtil.isNullOrBlank(car.getCarStyleId())) {
                        accept.setIsMatch(2);
                        accept.setCarName(car.getCarStyleName());
                        accept.setCarStyleId(car.getCarStyleId());
                        accept.setBrandId(car.getBrandId());
                        accept.setVendorId(car.getVendorId());
                        rtn = true;
                    }
                }
            }
	    }
	    return rtn;
	}
	/**
	 * 
	 * 将viewhelp中值set到entity中
	 * 
	 * @throws TmsDaoException
	 */
	private Car setEntityFromViewhelper(Car entity, TransferRgInputViewHelper view)
			throws TmsDaoException {
		entity.setVin(view.getVin());
		entity.setSerial(view.getBasicCarId());
		entity.setCarName(view.getCarName());
		entity.setEngine(view.getEngine());
		entity.setLicensePlate(view.getLicensePlate());
		if(view.getColor()!=null && !"".equals(view.getColor()))
		{
			entity.setColor(Integer.parseInt(view.getColor()));
		}else{
			entity.setColor(0);
		}
		entity.setRegDate(view.getRegDate());
		entity.setVendorCode(view.getVendorCode());
		entity.setModelCode(view.getModelCode());
		if(view.getCarUse()!=null && !"".equals(view.getCarUse()))
		{
			entity.setCarUse(Integer.parseInt(view.getCarUse()));
		}else{
			entity.setCarUse(0);
		}
		
		if(view.getCarType()!=null && !"".equals(view.getCarType()))
		{
			entity.setCarType(Integer.parseInt(view.getCarType()));
		}else{
			entity.setCarType(0);
		}
		
		entity.setSendCardDate(view.getSendCardDate());
		if(view.getCardType()!=null && !"".equals(view.getCardType()))
		{
			entity.setCardType(Integer.parseInt(view.getCardType()));
		}else{
			entity.setCardType(0);
		}
		entity.setRegisterCardNo(view.getRegisterCardNo());
		if(view.getCountryStyle()!=null && !"".equals(view.getCountryStyle()))
		{
			entity.setCountryStyle(Integer.parseInt(view.getCountryStyle()));
		}else{
			entity.setCountryStyle(0);
		}
		entity.setCompanyContactPerson(view.getCompanyContactPerson());

		//20160409
		if(!StringUtil.isNullOrBlank(view.getCarOwner()) && view.getCarOwner().length()>=5){
			entity.setOwnerType(2);//企业
			entity.setOwnerOrgNo(view.getIdentification());
	    } else if(!StringUtil.isNullOrBlank(view.getCarOwner()) && view.getCarOwner().length() < 5){
	    	entity.setOwnerType(1);//个人
	    	entity.setCarOwnerIdCardNo(view.getIdentification());
	    }

		entity.setOwnerPhone(view.getOwnerPhone());
		entity.setOwnerAddress(view.getOwnerAddress());
		entity.setCarOwner(view.getCarOwner());
		entity.setBrandId(view.getBrandId());
		entity.setCarStyleId(view.getCarStyleId());
		entity.setVendorId(view.getVendorId());
		return entity;
	}
	/**
	 * 
	 * 将viewhelp中值set到entity中
	 * 
	 * @throws TmsDaoException
	 */
	private TransferPersonalCarInfo setEntityFromViewhelper1(TransferPersonalCarInfo entity, TransferRgInputViewHelper view)
			throws TmsDaoException {
		entity.setVin(view.getVin());
		entity.setSerial(view.getBasicCarId());
		entity.setCarName(view.getCarName());
		entity.setEngine(view.getEngine());
		entity.setLicensePlate(view.getLicensePlate());
		if(view.getColor()!=null && !"".equals(view.getColor()))
		{
			entity.setColor(Integer.parseInt(view.getColor()));
		}else{
			entity.setColor(0);
		}
		entity.setRegDate(view.getRegDate());
		entity.setVendorCode(view.getVendorCode());
		entity.setModelCode(view.getModelCode());
		if(view.getCarUse()!=null && !"".equals(view.getCarUse()))
		{
			entity.setCarUse(Integer.parseInt(view.getCarUse()));
		}else{
			entity.setCarUse(0);
		}
		
		if(view.getCarType()!=null && !"".equals(view.getCarType()))
		{
			entity.setCarType(Integer.parseInt(view.getCarType()));
		}else{
			entity.setCarType(0);
		}
		
		entity.setSendCardDate(view.getSendCardDate());
		if(view.getCardType()!=null && !"".equals(view.getCardType()))
		{
			entity.setCardType(Integer.parseInt(view.getCardType()));
		}else{
			entity.setCardType(0);
		}
		entity.setRegisterCardNo(view.getRegisterCardNo());
		if(view.getCountryStyle()!=null && !"".equals(view.getCountryStyle()))
		{
			entity.setCountryStyle(Integer.parseInt(view.getCountryStyle()));
		}else{
			entity.setCountryStyle(0);
		}
		entity.setCompanyContactPerson(view.getCompanyContactPerson());

		//20160409
		if(!StringUtil.isNullOrBlank(view.getCarOwner()) && view.getCarOwner().length()>=5){
			entity.setOwnerType(2);//企业
			entity.setOwnerOrgNo(view.getIdentification());
	    } else if(!StringUtil.isNullOrBlank(view.getCarOwner()) && view.getCarOwner().length() < 5){
	    	entity.setOwnerType(1);//个人
	    	entity.setCarOwnerIdCardNo(view.getIdentification());
	    }

		//
		entity.setOwnerPhone(view.getOwnerPhone());
		entity.setOwnerAddress(view.getOwnerAddress());
		entity.setCarOwner(view.getCarOwner());
		entity.setBrandId(view.getBrandId());
		entity.setCarStyleId(view.getCarStyleId());
		entity.setVendorId(view.getVendorId());
		return entity;
	}
}
